const pbjs = require("protobufjs/cli/pbjs"); // or require("protobufjs/cli").pbjs / .pbts
const pbts = require("protobufjs/cli/pbts"); // or require("protobufjs/cli").pbjs / .pbts
const fs = require('fs')
const path = require('path')
const template = fs.readFileSync('./map.temp', {encoding: 'utf-8'})

const protoJsPath = path.join(__dirname, '../../assets/scripts/socket/proto', 'proto.js')
const protoTsPath = path.join(__dirname, '../../assets/scripts/socket/proto', 'proto.d.ts')
const mappingPath = path.join(__dirname, '../../assets/scripts/socket/proto', 'mapping.ts')

pbjs.main(["--target", "static-module", "-w", "commonjs", "-o", protoJsPath, "/Users/husong/svnProjects/AppProject/SumAPublicPro/doc/cocky.proto"], function (err, output) {
  if (err)
    throw err;
  pbts.main(["-o", protoTsPath, protoJsPath])
  generatorProtoId();
  // do something with output
});

function generatorProtoId() {
  const proto = require(protoJsPath)
  let content1 = "";
  let content2 = "";
  const template1 = "ID_TO_MSG.set($1, $2);"
  const template2 = "MSG_TO_ID.set($1, $2);"
  const result = JSON.parse(fs.readFileSync("/Users/husong/svnProjects/AppProject/SumAPublicPro/doc/protocol.json", {encoding: "utf-8"}))
  console.log(result)
  Object.keys(result).forEach(id => {
    const value = result[id];
    const cons = "proto." + value;
    content1 += template1.replace('$1', id.toString()).replace('$2', cons) + '\n'
    content2 += template2.replace('$1', cons).replace('$2', id.toString()) + '\n'
  });
  const out = template.replace('$content1', content1).replace('$content2', content2);
  fs.writeFileSync(mappingPath, out, {encoding: 'utf-8'})
}